#include <tT.h>
#include <env.h>

#include "can.h"
#include "adcinput.h"
#warning "ADCINPUT" 


// The throttle_t object and its initiation
ADCinput_t ADCinput = {tt_object(), 0,0,0,0,0,OFF,OFF,OFF,OFF,OFF,200};

void ADCRead(ADCinput_t *self, void *none);
//void ADCsendUART(ADCinput_t *self, void *none);

void ADCInit(ADCinput_t *self,void *none){
	//Setup the adc settings
	ADMUX = (1 << REFS0)|ADC6;	//ADC6 is the only ADC that wont disturbe anything else
	ADCSRA = (1 << ADIE)|(2);
	ADCSRA |= (1<<ADEN);
	//ADCSRB = (1<<AREFEN);
	
	//TT_AFTER(ENV_MSEC(500), self, ADCRead, TT_ARGS_NONE);
}

void ADCRead(ADCinput_t *self, void *none){
	TT_AFTER(ENV_MSEC(self->sampleTime), self, ADCRead, TT_ARGS_NONE);
	ADCSRA |= (1 << ADSC);
}

void ADConvertionComplete(void){
	switch(ADMUX & 0xF){
		case ADC4:
			ADCinput.ADC4val = ADCW;
			if(ADCinput.ADC5enabled)
				ADMUX = (1 << REFS0)|ADC5;
			else if(ADCinput.ADC6enabled)
				ADMUX = (1 << REFS0)|ADC6;
			else if(ADCinput.ADC8enabled)
				ADMUX = (1 << REFS0)|ADC8;
			else if(ADCinput.ADC9enabled)
				ADMUX = (1 << REFS0)|ADC9;
		case ADC5:
			ADCinput.ADC5val = ADCW;
			if(ADCinput.ADC6enabled)
				ADMUX = (1 << REFS0)|ADC6;
			else if(ADCinput.ADC8enabled)
				ADMUX = (1 << REFS0)|ADC8;
			else if(ADCinput.ADC9enabled)
				ADMUX = (1 << REFS0)|ADC9;
			else if(ADCinput.ADC4enabled)
				ADMUX = (1 << REFS0)|ADC4;
			break;
		case ADC6:
			ADCinput.ADC6val = ADCW;
			if(ADCinput.ADC8enabled)
				ADMUX = (1 << REFS0)|ADC8;
			else if(ADCinput.ADC9enabled)
				ADMUX = (1 << REFS0)|ADC9;
			else if(ADCinput.ADC4enabled)
				ADMUX = (1 << REFS0)|ADC4;
			else if(ADCinput.ADC5enabled)
				ADMUX = (1 << REFS0)|ADC5;
			break;
		case ADC8:
			ADCinput.ADC8val = ADCW;
			if(ADCinput.ADC9enabled)
				ADMUX = (1 << REFS0)|ADC9;
			else if(ADCinput.ADC4enabled)
				ADMUX = (1 << REFS0)|ADC4;
			else if(ADCinput.ADC5enabled)
				ADMUX = (1 << REFS0)|ADC5;
			else if(ADCinput.ADC6enabled)
				ADMUX = (1 << REFS0)|ADC6;
			break;
		case ADC9:
			ADCinput.ADC9val = ADCW;
			if(ADCinput.ADC4enabled)
				ADMUX = (1 << REFS0)|ADC4;
			else if(ADCinput.ADC5enabled)
				ADMUX = (1 << REFS0)|ADC5;
			else if(ADCinput.ADC6enabled)
				ADMUX = (1 << REFS0)|ADC6;
			else if(ADCinput.ADC8enabled)
				ADMUX = (1 << REFS0)|ADC8;
			break;
	}
}


ENV_INTERRUPT(ADC_vect, ADConvertionComplete);
